﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using Autofac;
using Cloak.Autofac;
using NHibernate;

namespace Cloak.Work.NHibernate.Autofac
{
	/// <summary>
	/// Registers a single session factory and a work context per lifetime scope
	/// </summary>
	public class NHibernateModule : BuilderModule
	{
		/// <summary>
		/// Initializes a module with the specification session configuration and work context type
		/// </summary>
		/// <param name="sessionConfiguration">The configuration to apply to NHibernate sessions</param>
		/// <param name="workContextType">The type of work context to create for each lifetime scope</param>
		public NHibernateModule(ISessionConfiguration sessionConfiguration, WorkContextType workContextType)
		{
			Contract.Requires(sessionConfiguration != null);

			RegisterInstance(sessionConfiguration.GetConfiguration().BuildSessionFactory()).SingleInstance();

			Register(c => c.Resolve<ISessionFactory>().OpenSession()).InstancePerLifetimeScope();

			if(workContextType == WorkContextType.Atomic)
			{
				RegisterType<AtomicWorkContext>().As<IWorkContext>().InstancePerLifetimeScope();
			}
			else
			{
				RegisterType<NonAtomicWorkContext>().As<IWorkContext>().InstancePerLifetimeScope();
			}
		}
	}
}